package handler

import (
	"cloud-disk/logic"
	"cloud-disk/model/request"
	"cloud-disk/model/response"
	"cloud-disk/util"
	"github.com/gin-gonic/gin"
	"net/http"
)

// UserLoginHandler 用户登录
func UserLoginHandler(c *gin.Context) {
	loginReq := request.Login{}
	c.BindJSON(&loginReq)
	user, err := logic.UserLoginLogic(loginReq)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg": "login fail ",
		})
		return
	}
	token, err := util.CreateToken(user.Id, user.Identity, user.Email)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg": "token fail ",
		})
		return
	}
	c.JSON(http.StatusOK, response.Login{Token: token})
}

// UserInfoHandler 用户信息
func UserInfoHandler(c *gin.Context) {
	id := c.GetInt("id")
	user, err := logic.UserInfoLogic(id)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg": "info error",
		})
		return
	}
	c.JSON(http.StatusOK, response.Info{
		Name:  user.Name,
		Email: user.Email,
		Phone: user.Phone,
	})
}

// UserCaptchaHandler 获取验证码
func UserCaptchaHandler(c *gin.Context) {
	req := request.Captcha{}
	err := c.BindJSON(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg": "captcha request fail",
		})
		return
	}
	err = logic.UserSendCaptchaLogic(req.Email, req.Mode)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, "ok")
}

// UserRegisterHandler 用户注册
func UserRegisterHandler(c *gin.Context) {
	regReq := request.Register{}
	c.BindJSON(&regReq)
	var err error
	err = logic.UserRegisterLogic(regReq)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"msg": err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, "ok")
}
